package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.utils;
import com.zhouyou.view.seekbar.SignSeekBar;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/2/12.
 */

public class DeviceRelation_ChaZuoActivity extends BaseActivity {
    private TextView seekbar1_text, seekbar2_text, seekbar3_text, kaiguan1_text, kaiguan2_text, kaiguan3_text;
    private SignSeekBar seekbar1, seekbar2, seekbar3;
    private DrawableSwitch switch1, switch2, switch3;
    MineZigBeeDeviceListEntity bean;
    private ImageView img;
    private int type = ConstantConfigure.TYPE_CONTROL;
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicerelation_chazuo);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = bean.getUuid();
        model = bean.getModel();
        type = getIntent().getIntExtra("type", ConstantConfigure.TYPE_CONTROL);
        setView();
        setTitle(true, false, "添加关联");
        showRight(true, R.mipmap.head_title_tick);
        //点击右上角保存此时设备状态与关联场景
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        //初始化后，数据库查询当前设备关联情况，无关联则查询最新状态
        getDeviceDetailInfo();
    }

    private void save() {
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setModel(model);
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        if (switch1.isSwitchOn()) {
            sb.append("\"SwitchChildLock\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("1");
            sb.append(entity.toString());
            sb.append(",");
        } else {
            sb.append("\"SwitchChildLock\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("0");
            sb.append(entity.toString());
            sb.append(",");
        }
        if (switch2.isSwitchOn()) {
            sb.append("\"SwitchMultiple_1\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("1");
            sb.append(entity.toString());
            sb.append(",");
        } else {
            sb.append("\"SwitchMultiple_1\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("0");
            sb.append(entity.toString());
            sb.append(",");
        }
        if (switch3.isSwitchOn()) {
            sb.append("\"SwitchMultiple_2\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("1");
            sb.append(entity.toString());
            sb.append(",");
        } else {
            sb.append("\"SwitchMultiple_2\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("0");
            sb.append(entity.toString());
            sb.append(",");
        }

        sb.append("\"RmsCurrent\" :");
        Key_ValueEntity entity_dianliu = new Key_ValueEntity();
        entity_dianliu.setValue(String.valueOf(seekbar1.getProgress()));
        sb.append(entity_dianliu.toString());
        sb.append(",");
        sb.append("\"RmsVoltage\" :");
        Key_ValueEntity entity_dianya = new Key_ValueEntity();
        entity_dianya.setValue(String.valueOf(seekbar2.getProgress()));
        sb.append(entity_dianya.toString());
        sb.append(",");
        sb.append("\"SumElectric\" :");
        Key_ValueEntity entity_dianliang = new Key_ValueEntity();
        entity_dianliang.setValue(String.valueOf(seekbar3.getProgress()));
        sb.append(entity_dianliang.toString());
        sb.append(",");
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        Log.i("info","设置的情景id是" + relationDeviceTable.getQingJingTable_id());
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ?", uuid).find(LocalDb_RelationDeviceTable.class);
        Log.i("info", "此时的关联表长度=" + lists.size());
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
       finish();
        toastActBtm("保存成功");
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicerelation_img);
        String imgurl = null;
        seekbar1_text = (TextView) findViewById(R.id.activity_devicerelation_seekbar1_text);
        seekbar2_text = (TextView) findViewById(R.id.activity_devicerelation_seekbar2_text);
        seekbar3_text = (TextView) findViewById(R.id.activity_devicerelation_seekbar3_text);
        kaiguan1_text = (TextView) findViewById(R.id.activity_devicerelation_kaiguan1_text);
        kaiguan2_text = (TextView) findViewById(R.id.activity_devicerelation_kaiguan2_text);
        kaiguan3_text = (TextView) findViewById(R.id.activity_devicerelation_kaiguan3_text);
        seekbar1 = (SignSeekBar) findViewById(R.id.activity_devicerelation_seekbar1);
        seekbar2 = (SignSeekBar) findViewById(R.id.activity_devicerelation_seekbar2);
        seekbar3 = (SignSeekBar) findViewById(R.id.activity_devicerelation_seekbar3);
        switch1 = (DrawableSwitch) findViewById(R.id.activity_devicerelation_kaiguan1);
        switch2 = (DrawableSwitch) findViewById(R.id.activity_devicerelation_kaiguan2);
        switch3 = (DrawableSwitch) findViewById(R.id.activity_devicerelation_kaiguan3);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_ChaZuoActivity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end
        if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            imgurl = ConstantConfigure.IMGURL_10AZHINENGCHAZUO_000A1E11;
            seekbar1_text.setText("有效电流");
            seekbar2_text.setText("有效电压");
            seekbar3_text.setText("电量统计");
            kaiguan1_text.setText("童锁开关");
            kaiguan2_text.setText("插孔开关1");
            kaiguan3_text.setText("插孔开关2");

            seekbar1.getConfigBuilder()
                    .min(0)
                    .max(10)
                    .progress(2)
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_ChaZuoActivity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("A")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekbar2.getConfigBuilder()
                    .min(0)
                    .max(500)
                    .progress(220)
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_ChaZuoActivity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("V")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekbar3.getConfigBuilder()
                    .min(0)
                    .max(9999)
                    .progress(1)
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_ChaZuoActivity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("KWh")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            switch1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch1.isSwitchOn() ? 0 : 1;
                    switch1.setSwitchOn(!switch1.isSwitchOn());
                    switch1.invalidate();
                }
            });
            switch2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch2.isSwitchOn() ? 0 : 1;
                    switch2.setSwitchOn(!switch2.isSwitchOn());
                    switch2.invalidate();
                }
            });
            switch3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int state = switch3.isSwitchOn() ? 0 : 1;
                    switch3.setSwitchOn(!switch3.isSwitchOn());
                    switch3.invalidate();
                }
            });
        }
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);

                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            Key_ValueEntity bean1 = JSON.parseObject(obj.getString("SwitchChildLock"), Key_ValueEntity.class);
            Key_ValueEntity bean2 = JSON.parseObject(obj.getString("SwitchMultiple_1"), Key_ValueEntity.class);
            Key_ValueEntity bean3 = JSON.parseObject(obj.getString("SwitchMultiple_2"), Key_ValueEntity.class);

            Key_ValueEntity bean4 = JSON.parseObject(obj.getString("RmsCurrent"), Key_ValueEntity.class);
            Key_ValueEntity bean5 = JSON.parseObject(obj.getString("RmsVoltage"), Key_ValueEntity.class);
            Key_ValueEntity bean6 = JSON.parseObject(obj.getString("SumElectric"), Key_ValueEntity.class);
            float progress_bean4 = (float) Double.parseDouble(bean4.getValue());
            float progress_bean5 = (float) Double.parseDouble(bean5.getValue());
            float progress_bean6 = (float) Double.parseDouble(bean6.getValue());
            seekbar1.setProgress(progress_bean4);
            seekbar2.setProgress(progress_bean5);
            seekbar3.setProgress(progress_bean6);
            if (bean1.getValue().equals("0")) {
                switch1.setSwitchOn(false);
            } else {
                switch1.setSwitchOn(true);
            }
            switch1.invalidate();
            if (bean2.getValue().equals("0")) {
                switch2.setSwitchOn(false);
            } else {
                switch2.setSwitchOn(true);
            }
            switch2.invalidate();
            if (bean3.getValue().equals("0")) {
                switch3.setSwitchOn(false);
            } else {
                switch3.setSwitchOn(true);
            }
            switch3.invalidate();
        }
    }

    private String translateParams() {
        //0关闭，1开启
        Map<String, String> params = new HashMap<>();
        if (switch1.isSwitchOn()) {
            params.put("SwitchChildLock", "1");
        } else {
            params.put("SwitchChildLock", "0");
        }
        if (switch2.isSwitchOn()) {
            params.put("SwitchMultiple_1", "1");
        } else {
            params.put("SwitchMultiple_1", "0");
        }
        if (switch3.isSwitchOn()) {
            params.put("SwitchMultiple_2", "1");
        } else {
            params.put("SwitchMultiple_2", "0");
        }
        return utils.getTheJson(params);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }
}
